package com.mygame.center.service;

import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.mygame.common.error.IServerError;
import com.mygame.common.utils.CommonField;
import com.mygame.dao.UserAccountDao;
import com.mygame.db.entity.UserAccount;
import com.mygame.http.request.LoginParam;

@Service
public class UserLoginService {

    @Autowired
    private UserAccountDao userAccountDao;
    private Logger logger = LoggerFactory.getLogger(UserLoginService.class);


    public IServerError verfiyLoginParam(LoginParam loginParam) {

        return null;
    }

    public IServerError verfiySdkToken(String openId, String token) {
        // 这里调用sdk服务端验证接口

        return null;
    }

    public UserAccount login(LoginParam loginParam) {
        
        String openId = loginParam.getOpenId();
        openId = openId.intern();//放openId放入到常量池
        synchronized (openId) {// 对openId加锁，防止用户点击多次注册多次
            Optional<UserAccount> op = userAccountDao.findById(openId);
            UserAccount userAccount = null;
            if (!op.isPresent()) {
                // 用户不存在，自动注册
                userAccount = this.register(loginParam);
            } else {
                userAccount = op.get();
            }
            return userAccount;
        }
    }

    private UserAccount register(LoginParam loginParam) {

        long userId = userAccountDao.getNextUserId();// 使用redis自增保证userId全局唯一
        UserAccount userAccount = new UserAccount();
        userAccount.setOpenId(loginParam.getOpenId());
        userAccount.setCreateTime(System.currentTimeMillis());
        userAccount.setUserId(userId);
        this.updateUserAccount(userAccount);
        logger.debug("user {} 注册成功", userAccount);
        return userAccount;

    }

    public void updateUserAccount(UserAccount userAccount) {
        this.userAccountDao.saveOrUpdate(userAccount, userAccount.getOpenId());
    }

    public Optional<UserAccount> getUserAccountByOpenId(String openId) {
        return this.userAccountDao.findById(openId);
    }

    public long getUserIdFromHeader(HttpServletRequest request) {
        String value = request.getHeader(CommonField.USER_ID);
        long userId = 0;
        if (!StringUtils.isEmpty(value)) {
            userId = Long.parseLong(value);
        }
        return userId;

    }
    public String getOpenIdFromHeader(HttpServletRequest request) {
        return request.getHeader(CommonField.OPEN_ID);
    }
    public static void main(String[] args) {
        LoginParam loginParam = new LoginParam();
        loginParam.setOpenId("aaaaaa");
        String json = JSON.toJSONString(loginParam);
        
        LoginParam loginParam2 = JSON.parseObject(json, LoginParam.class);
        LoginParam loginParam3 = JSON.parseObject(json,LoginParam.class);
        System.out.println(loginParam2.getOpenId() == loginParam3.getOpenId());//（1）这里输出false
        String openId1 = loginParam2.getOpenId().intern();
        String openId2 = loginParam3.getOpenId().intern();
        System.out.println(openId1 == openId2);//(2) 这里输出true
        String a = "ccccc";
        String b = "ccccc";
        String c = new String("ccccc");
        System.out.println(a==b);
        System.out.println(a== c);
    }

}
